package com.epro.dx.activity;

import com.epro.dx.R;
import com.epro.dx.listenner.MyAsyncTaskListenner;
import com.epro.dx.task.GetActiveInfoAsyncTask;
import com.epro.dx.util.AsyncTaskUtil;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.model.ActiveModel;
import com.weipu.common.util.GlobalConfig;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.widget.RelativeLayout;
import android.net.http.SslError;
import android.graphics.Bitmap;

/**
 * @author tony
 * Banner使用原生页面打开URL页面
 */
@SuppressLint("JavascriptInterface")
public class LPLocalBrowserActivity extends BaseFragmentActivity {
	
	private WebView webView;
	private String url;
	private String title;
	private boolean isFromMessage;
	private boolean isShowWaitingDialog;
	private RelativeLayout invalidActiveLayout;
	private boolean needCheckValid;
	private String noticeID;
	private RelativeLayout refreshBtn;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_lp_localbrowser);
		
		initView();
		getDataFromIntent();
		if(needCheckValid){
			GetActiveInfoAsyncTask getActiveInfoAsyncTask = new GetActiveInfoAsyncTask(3, noticeID, new MyAsyncTaskListenner() {
				
				@Override
				public void onPreTask() {
					showWaitingDialog();
				}
				
				@Override
				public void onPostTask(String result, Object obj) {
					hideWaitingDialog();
					if("0".equals(result) && null!=obj){
						ActiveModel model = (ActiveModel)obj;
						if(model.getState() == ActiveModel.STATE_OFFLINE || model.getState() == ActiveModel.STATE_STOP){
							invalidActiveLayout.setVisibility(View.VISIBLE);
							refreshBtn.setClickable(false);
							return;
						}
					}
					initwebview();
				}
			});
			AsyncTaskUtil.executeTask(getActiveInfoAsyncTask);
		}else{
			initwebview();
		}
	}

	private void getDataFromIntent() {
		Intent intent = getIntent();
		title = intent.getStringExtra("PageTitle");
		url = intent.getStringExtra("URL");
		isFromMessage = intent.getBooleanExtra("IsFromMessage", false);
		needCheckValid = intent.getBooleanExtra("needCheckValid", false);
		noticeID = intent.getStringExtra("NoticeID");
	}

	private void initView() {
		// 标题
		setLeftBtnContent(true, -1);
		setTitleContent("LP Test");
		
		webView = (WebView) findViewById(R.id.lp_localbrowser_webview);
		refreshBtn = (RelativeLayout) findViewById(R.id.lp_localbrowser_refresh_btn);
		refreshBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// 清楚缓存重新加载网页
				if(null!=webView){
					webView.clearCache(true);
				}
				initwebview();
			}
		});
		invalidActiveLayout = (RelativeLayout) findViewById(R.id.layout_invalid_active);
		
		topbarLeftTv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(isFromMessage){
					backToHome();
				}else{
					finish();
				}
			}
		});
	}
	
	@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
	private void initwebview() {
		showWaitingDialog();
		isShowWaitingDialog=true;
		webView.setFocusableInTouchMode(true);
		webView.getSettings().setSupportZoom(true);
		webView.getSettings().setBuiltInZoomControls(true);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.addJavascriptInterface(new HtmlObject(), "dmsObj"); 

		webView.setWebViewClient(new WebViewClient() {
			// 跳过HTTPS验证
			@Override
			public void onReceivedSslError(WebView view,
					SslErrorHandler handler, SslError error) {
				if(GlobalConfig.getInstance().isCheckSSL()){
            		handler.proceed();
            	}else{
            		handler.cancel();
            	}
			}
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				shouldOverrideUrlLoading(view, url);
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public boolean shouldOverrideUrlLoading(final WebView view, String url) {
				// 自适应屏幕
				view.getSettings().setUseWideViewPort(true);
				view.getSettings().setLoadWithOverviewMode(true);
				return super.shouldOverrideUrlLoading(view, url);
			}

		});
		webView.setWebChromeClient(new WebChromeClient() {
			
			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					JsResult result) {
				return super.onJsAlert(view, url, message, result);
			}
			
			@Override
			public boolean onJsConfirm(WebView view, String url,
					String message, JsResult result) {
				return super.onJsConfirm(view, url, message, result);
			}
			
			@Override
			public boolean onJsPrompt(WebView view, String url, String message,
					String defaultValue, JsPromptResult result) {
				return super.onJsPrompt(view, url, message, defaultValue, result);
			}
			
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
//				view.requestFocus();
				if (isShowWaitingDialog && newProgress >= 20) {
					hideWaitingDialog();
					isShowWaitingDialog=false;
				}
			}
		});
		if(!TextUtils.isEmpty(title)){
			setTitleContent(title);
		}
		if(!TextUtils.isEmpty(url)){
			webView.loadUrl(url);
		}
	}
	
	private class HtmlObject {
		public HtmlObject(){
			
		}
		@JavascriptInterface
		public void appProductDetail(int sku) {
			detailIntent(sku);
		}

	}
	
	protected void detailIntent(int sku) {
		Intent intent = new Intent(this, DetailActivity.class);
		Bundle data = new Bundle();

		data.putInt(ServerConstant.Parameter.PARAMETER_NAME_PRODUCT_ID,
				sku);
		data.putString(ServerConstant.Parameter.PARAMETER_NAME_BACK_ACTION,
				ServerConstant.ActionConstant.ACTION_GADGET);
		data.putString(ServerConstant.Parameter.PARAMETER_NAME_FROM_ACTIVITY,
				ServerConstant.ActionConstant.ACTION_GADGET);
		intent.putExtras(data);

		startActivity(intent);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			if(webView.canGoBack()){
				webView.goBack();
				return true;
			}else if(isFromMessage){
				backToHome();
			}else{
				finish();
			}
		}
		return super.onKeyDown(keyCode, event);
	}
}
